<!-- z-paging聊天item -->

<template>
	<view class="chat-item">
		<view :class="{'chat-container': true, 'chat-location-me': item.type == 1}">
			<view class="chat-icon-container">
				<view class="chat-icon-box">
					<image class="chat-icon" :src="item.icon" mode="aspectFill" />
				</view>
			</view>
			<view class="chat-content-container">
				<view class="chat-text-container-super" :style="[{justifyContent:item.type==1?'flex-end':'flex-start'}]">
					<view :class="{'chat-text-container': true, 'chat-text-container-me': item.type == 1}">
						<view class="bubble">
							<view :class="{'chat-text':true,'chat-text-me': item.type == 1}">
								<view v-if="item.content">
									<view v-if="item.content.indexOf('doctorAdvice') > -1">
										<view v-html="item.content.substring(12)"></view>
									</view>
									<view v-else>
										<!--<view v-html="item.content"></view>-->
										<!--<rich-text space="nbsp" :nodes="item.content"></rich-text>-->
										<text space="nbsp" user-select="true">{{item.content}}
											<text v-if="item.type == 0 && !item.end" class="cursor">|</text>
										</text>
									</view>
								</view>
								<view v-else><u-loading style="height: 20px;width: 20px;"></u-loading></view>
							</view>
						</view>
					</view>
				</view>
				<view v-if="item.type==0 && item.end" style="padding-top: 6px;display: flex;justify-content: flex-start;align-items: center;">
					<!-- <uni-icons type="sound" size="30" ></uni-icons> -->
					<text class="icon iconfont icon-laba" v-if="!isSpeaking" @click="startSpeechSynthesis(item.content)"></text>
					<view  v-else class="bofangzhongOuter">
						<image class="bofangzhongBox" @click="stopSpeechSynthesis" src="/static/icon/bofangzhong.gif"></image>
					</view>
					<text class="confirmBtn"  v-if="item.content.indexOf('doctorAdvice') > -1">确认提交</text>

					<!-- <button @click="stopSpeechSynthesis">停止朗读</button> -->
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name:"chat-item",
		props: {
			item: {
				type: Object,
				default: function() {
					return {
						time: '',
						icon: '',
						name: '',
						content: '',
						isMe: false
					}
				}
			},
			index: '',
			currentContent: ''
		},
		data() {
			return {
				textToSpeak: "如果需要更精确或者跨平台的语音识别支持！",
				isSpeaking: false, //
				utterance: null, // SpeechSynthesisUtterance 实例
			};
		},
		methods:{
			// 预览图片
			showPic(msg){
				let imagesUrl = [msg.data.url];
				uni.previewImage({
					urls:imagesUrl
				});
			},
			downloadFile(data)
			{
				// #ifdef H5
					window.open(data.data.url,'_blank');
				// #endif
			},
			playSpeech() {
				if (!this.inputText) {
					uni.showToast({
						title: '请输入要转换为语音的文字',
						icon: 'none'
					});
					return;
				}
				// 取消当前正在播放的语音
				if (this.currentUtterance && this.speechSynthesis.speaking) {
					this.speechSynthesis.cancel();
					this.currentUtterance = null;
				}
				// 创建新的语音合成实例
				const newUtterance = new SpeechSynthesisUtterance(this.inputText);
				newUtterance.onend = () => {
					this.currentUtterance = null;
				};
				this.currentUtterance = newUtterance;
				this.speechSynthesis.speak(newUtterance);
			},
			clearHandle(){
				console.log('343434');
				this.isSpeaking = false;
				this.utterance = null;
				speechSynthesis.cancel(); 
				
			},
			startSpeechSynthesis(textToSpeak){
				console.log(this.currentContent, 'this.currentContent')
				console.log('准备中')
				uni.showLoading({
					title: '转译中'
				});
				let _this = this
				uni.request({
					url: '/yuyin-admin/yuyin/getYuYin2', // 替换为实际的 API 地址
					method: 'get',
					data: {
						// text: 'ff',
						text: this.currentContent ? this.currentContent : textToSpeak,
					},
					success: function (res) {
						let bbb = 'data:audio/mp3;base64,' + res.data.byte
						const blob = _this.base64ToBlob(bbb);
						const url = URL.createObjectURL(blob);
						const innerAudioContext = uni.createInnerAudioContext();
						innerAudioContext.src = url;
						innerAudioContext.autoplay = true;
						console.log('开始啦')
						uni.hideLoading()
						innerAudioContext.onPlay(() => {
							console.log("音频开始播放");
							_this.isSpeaking = true;
						});
						innerAudioContext.onEnded(() => {
							console.log('音频播放结束');
							_this.isSpeaking = false;
						});
						innerAudioContext.onError((err) => {
							console.error("播放音频出错:", err);
							_this.isSpeaking = false;
						});
					},
					fail: function (err) {
						console.error('请求失败:', err)
					},
					complete: function () {
						console.log('请求完成')
					}
				})
			},
			base64ToBlob(base64) {
				const byteString = atob(base64.split(',')[1]); // 去掉 'data:audio/mp3;base64,' 部分
				const arrayBuffer = new ArrayBuffer(byteString.length);
				const uint8Array = new Uint8Array(arrayBuffer);
				for (let i = 0; i < byteString.length; i++) {
					uint8Array[i] = byteString.charCodeAt(i);
				}
				return new Blob([arrayBuffer], { type: 'audio/mp3' }); // 这里 'audio/mp3' 可以根据实际音频类型调整
			},
			// 初始化并开始文字转语音
			  startSpeechSynthesis1(textToSpeak) {
			    this.$emit("customEvent")
				// 检查浏览器是否支持 SpeechSynthesis API
				setTimeout(() => {
					if ('speechSynthesis' in window) {
						
					  this.isSpeaking = true;
					  // 创建一个 SpeechSynthesisUtterance 实例
					  this.utterance = new SpeechSynthesisUtterance(textToSpeak);
					  
					  // 设置语音的语言（中文）
					  this.utterance.lang = 'zh-CN';
								
					  // 可以设置语速、音调等属性
					  this.utterance.rate = 1; // 语速（0.1 到 10）
					  this.utterance.pitch = 1; // 音调（0 到 2）
						
					  // 开始朗读
					  speechSynthesis.speak(this.utterance);
					  console.log("开始朗读文字:", textToSpeak);
					  this.utterance.onend = () => {
						  
						  console.log('3243434')
					  };
					} else {
					  console.log("当前浏览器不支持文字转语音功能");
					}
				}, 10)
				
			    
			  },
			
			  // 停止朗读
			  stopSpeechSynthesis() {
			    if (this.utterance) {
				  this.isSpeaking = false;
			      speechSynthesis.cancel(); // 停止朗读
			      console.log("停止朗读");
			    }
			}
		}
	}
</script>

<style lang="scss">
	.labaBox{
		height: 30px;
		width: 30px;
		display: block;
		background: url('/static/icon/laba.png');
		background-size: 100% 100%;
	}

	.bofangzhongOuter{
		height: 30px;
		width: 30px;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 100%;
		box-shadow: 0px 1px 4px 0px rgba(0,0,0,0.15);
		.bofangzhongBox{
			height: 24px;
			width: 24px;
		}
	}
	.confirmBtn{
		background: #FFFFFF;
		box-shadow: 0px 1px 4px 0px rgba(0,0,0,0.15);
		border-radius: 4px 4px 4px 4px;
		font-weight: 500;
		font-size: 12px;
		color: #10BA6B;
		padding: 0 8px;
		margin-left: 10px;
		height: 30px;
		line-height: 30px;
	}
	.icon-laba{
		box-shadow: 0px 1px 4px 0px rgba(0,0,0,0.15);
		height: 30px;
		width: 30px;
		display: block;
		background: #fff;
		border-radius: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.chat-item {
		display: flex;
		flex-direction: column;
		padding: 10px;
	}
	.chat-time {
		padding: 2px 0px;
		text-align: center;
		font-size: 11px;
		color: #aaaaaa;
	}
	.chat-container {
		display: flex;
		flex-direction: row;
	}
	.chat-location-me {
		flex-direction: row-reverse;
		text-align: right;
	}
	.chat-icon-container {
		margin-top: 6px;
	}
	.chat-icon-box{
		height: 35px;
		width: 35px;
		background-color: #eeeeee;
		border-radius: 100%;
		position: relative;
	}
	.chat-icon{
		position: absolute;
		left: 0;
		bottom: 0;
		width: 35px;
		height: 35px;
		border-radius: 50%;
		background-color: #eeeeee;
	}
	.chat-content-container {
		width: 100%;
		margin: 0px 7px;
	}
	.chat-user-name{
		font-size: 13px;
		color: #888888;
	}
	.chat-text-container {
		text-align: left;
		background-color: #f3f4f5;
		border-radius: 8px;
		padding: 8px 15px;
		margin-top: 5px;
		max-width: calc(100% - 29px);

	}
	.chat-text-container-me {
		background-color: #d6f5e5;
	}
	.chat-text-container-super {
		display: flex;
		flex-direction: row;
		width: auto;
	}
	.chat-text {
		font-size: 14px;
		/* #ifndef APP-NVUE */
		word-break: break-all;
		/* #endif */
		/* #ifdef APP-NVUE */
		max-width: 250px;
		/* #endif */
	}
	.chat-text-me {
		color: #333;
	}
	.img{
		/* #ifndef APP-NVUE */
		max-width: 250px;
		/* #endif */
	}
	.bubble{
		width: 100%;
		.iconfont {
			font-size:21px;
			margin-right: 4px;
		}
	}
	.chat-text-container{
		.bubble{
			color: #333;
			.iconfont {
				color:#333;
			}
		}
	}
	.chat-text-container-me{
		.bubble{
			color:#FFFFFF;
			.iconfont {
				color:#FFFFFF;
			}
		}
	}
	.cursor {
		margin-right: 5px;
		animation: blink 0.7s step-end infinite;
		font-size: 16px;
		display: inline-block;
	}
	.chatTitle{
		font-size: 16px;
		font-weight: 600;
	}
	.chatDes{
		font-size: 14px;
		font-weight: 400;
		padding: 2px 0 10px;
	}

	@keyframes blink {
		from, to { opacity: 0; }
		50% { opacity: 1; }
	}
</style>